﻿using System;
using System.IO;
using System.Xml;

namespace Toybox.NicoSharp.Video.Primitives
{
	using Message;

	public abstract partial class AbstractPacketCreator
	{

		#region Constructor

		public AbstractPacketCreator(Flv flv)
		{
			if (flv == null)
				throw new ArgumentNullException("flv");

			this.Flv = flv;

			this.RequestedTypes = ThreadTypes.All;
			this.Scores = true;
			this.Nicoru = true;
			this.When = null;
		}

		#endregion Constructor


		#region Public Members

		public ThreadTypes RequestedTypes { get; set; }

		public bool Scores { get; set; }

		public bool Nicoru { get; set; }

		public DateTime? When { get; set; }

		public int LanguageId { get; set; }


		public Thread Thread { get; set; }

		#endregion Public Members

		#region Protected Members

		protected Flv Flv { get; set; }

		protected ThreadKey CommunityThreadKey { get; set; }

		#endregion Protected Members


		#region Public Methods

		public override string ToString()
		{
			XmlDocument doc = new XmlDocument();
			doc.AppendChild(doc.CreateElement("packet"));

			this.CreateDocument(ref doc);

			try
			{
				using (var sw = new StringWriter())
				using (var tw = new XmlTextWriter(sw))
				{
					doc.WriteTo(tw);
					return sw.ToString();
				}
			}
			catch
			{
				return null;
			}
		}

		#endregion Public Methods

		#region Protected Methods

		protected abstract void CreateDocument(ref XmlDocument doc);

		protected bool CheckThreadType(ThreadTypes type)
		{
			return this.RequestedTypes.HasFlag(type) && this.Flv.ThreadTypes.HasFlag(type);
		}

		protected int CoerceResFrom(int res_from)
		{
			if (this.Flv.l < 60)
				return res_from < 100 ? res_from : 100;
			if (this.Flv.l < 300)
				return res_from < 250 ? res_from : 250;
			if (this.Flv.l < 600)
				return res_from < 500 ? res_from : 500;

			return res_from < 1000 ? res_from : 1000;
		}

		#endregion Protected Methods

	}
}